<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'rd:rd10:rdrecord10:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="70%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdrecords10List>
        <a-button class="mb-2" @click="handleRdrecords10Add" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <a-button class="ml-2" @click="handleBatchSetDcstockname" v-auth="'rd:rd10:rdrecord10:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('批量设置仓库') }}
        </a-button>
        <BasicTable @register="registerRdrecords10Table" @row-click="handleRdrecords10RowClick">
          <template #fstockid>
            <span class="required-asterisk">*</span>{{ t('仓库名称') }}
          </template>
          <template #fqty>
            <span class="required-asterisk">*</span>{{ t('应收数量') }}
          </template>
        </BasicTable>
      </template>
    </BasicForm>
    <ListSelect
      ref="listSelectRef"
      :selectList="selectListRef"
      selectType="basInvSelect"
      :queryParams="queryParams"
      :checkbox="true"
      @select="handleSelect"
      v-show="false"
    />
    <!-- 批量设置仓库弹窗 -->
    <BatchSetDcstockname @register="registerBatchSetModal" @success="handleBatchSetSuccess" />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsRdRd10Rdrecord10Form">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { Rdrecord10, rdrecord10Save, rdrecord10Form } from '/@/api/wms/rd/rd10/rdrecord10';
  import { companyTreeData } from '/@/api/sys/company';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { Table, TableSummary, TableSummaryCell, TableSummaryRow } from 'ant-design-vue';
  import { ListSelect } from '/@/components/ListSelect';
  import { useUserStore } from '/@/store/modules/user';
  import { useModal } from '/@/components/Modal';
  import BatchSetDcstockname from '/@/views/wms/rd/rd08/rdrecord08/batchSetDcstockname.vue';
  const userStore = useUserStore();

  // 保存上一个公司代码值
  let previousCompanyCode = ref('');

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('rd.rd10.rdrecord10');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<Rdrecord10>({} as Rdrecord10);
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);
  const queryParams = ref({});

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增入库任务单') : t('编辑入库任务单'),
  }));

  // 批量设置调入仓库模态框
  const [registerBatchSetModal, { openModal: openBatchSetModal }] = useModal();

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('公司名称'),
      field: 'companyCode',
      fieldLabel: 'companyName',
      component: 'TreeSelect',
      componentProps: {
        api: companyTreeData,
        allowClear: true,
        onChange: (value, option) => {
          // 检查是否有明细数据
          const tableData = rdrecords10Table.getDataSource();
          if (tableData && tableData.length > 0) {
            const { createConfirm } = useMessage();
            createConfirm({
              iconType: 'warning',
              title: '确认操作',
              content: '切换公司会清空所有明细数据，是否继续？',
              onOk: () => {
                // 用户确认后清空明细数据
                rdrecords10Table.setTableData([]);
                // 更新保存的值
                previousCompanyCode.value = value;
              },
              onCancel: () => {
                // 用户取消，恢复到上一个值
                setTimeout(() => {
                  setFieldsValue({ companyCode: previousCompanyCode.value });
                }, 0);
              }
            });
          } else {
            // 没有明细数据时，直接更新保存的值
            previousCompanyCode.value = value;
          }
          queryParams.value = {
            companyCode: value,
          };
        },
      },
      required: true,
    },
    {
      label: t('单据编号'),
      field: 'fbillno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('数据来源'),
      field: 'sourceFlag',
      component: 'Select',
      componentProps: {
        dictType: 'bas_source_type',
      },
      dynamicDisabled: true,
    },
    {
      label: t('红蓝标志'),
      field: 'bred',
      component: 'Select',
      componentProps: {
        dictType: 'wms_bred_status',
      },
      required: true,
    },
    {
      label: t('单据日期'),
      field: 'fdate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        valueFormat: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
    },
    // {
    //   label: t('业务类型'),
    //   field: 'ftype',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    // },
    // {
    //   label: t('采购方式'),
    //   field: 'fpomode',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 100,
    //   },
    // },
    // {
    //   label: t('供应商内码'),
    //   field: 'fsupplyid',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    // },
    {
      label: t('供应商名称'),
      field: 'fsuppliername',
      component: 'Input',
      componentProps: {
        maxlength: 255,
      },
      required: true,
    },
    {
      label: t('供应商编码'),
      field: 'fsupplierno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
    },
    {
      label: t('备注'),
      field: 'fexplanation',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('入库明细'),
      field: 'rdrecords10List',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdrecords10List',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate, getFieldsValue }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerRdrecords10Table, rdrecords10Table] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRdrecords10Delete.bind(this, record),
          },
          auth: 'rd:rd10:rdrecord10:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
    showCustomSummary: true,
    rowSelection: {
      type: 'checkbox',
    },
  });

  async function setRdrecords10TableData(_res: Recordable) {
    rdrecords10Table.setColumns([
      // {
      //   title: t('行号'),
      //   dataIndex: 'fentryid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 20,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('物料内码'),
      //   dataIndex: 'fitemid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      {
        title: t('物料代码'),
        // dataIndex: 'fitemno',
        dataIndex: 'basInv.viewCode',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('物料名称'),
        dataIndex: 'fitemname',
        width: 180,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('形象刊'),
        dataIndex: 'freeVO.cfree1',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      // {
      //   title: t('辅助属性'),
      //   dataIndex: 'f109',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 100,
      //   },
      //   editRule: false,
      // },
     
      // {
      //   title: t('仓库编码'),
      //   dataIndex: 'fstockid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('仓库名称'),
      //   dataIndex: 'fstockname',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 255,
      //   },
      //   editRule: false,
      // },
      {
        title: t('仓库名称'),
        dataIndex: 'fstockid',
        slots: { title: 'fstockid' },
        dataLabel: 'fstockname',
        width: 100,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: ({ record }) => {
          return {
            api: basWarehouseTreeData,
            canSelectParent: false,
            showSearch: false,
            allowClear: true,
            onChange: (value, label) => {
              rdrecords10Table.updateTableDataRecord(record.id, {
                ...record,
                fstockno: value,
                fstockname: label,
                fstockid: value,
              });
            },
          };
        },
        editRule: true,
      },
      {
        title: t('应收数量'),
        dataIndex: 'fqty',
        slots: { title: 'fqty' },
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: true,
        showSummary: true,
      },
      {
        title: t('实收数量'),
        dataIndex: 'sumRkQty',
        width: 80,
        align: 'center',
        editRow: false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
        showSummary: true,
      },
      // {
      //   title: t('采购订单主表ID'),
      //   dataIndex: 'forderid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('采购订单单号'),
      //   dataIndex: 'forderno',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: false,
      // },
      // {
      //   title: t('采购订单行号'),
      //   dataIndex: 'forderentryid',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 20,
      //   },
      //   editRule: false,
      // },
      {
        title: t('行备注'),
        dataIndex: 'fremarks',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
    ]);

    // 确保所有行都有唯一ID并处于可编辑状态
    const tableData = (record.value.rdrecords10List || []).map((item: any, index: number) => ({
      ...item,
      id: item.id || new Date().getTime() + index,
      editable: true, // 强制设置为可编辑，确保验证回调被初始化
    }));

    rdrecords10Table.setTableData(tableData);

    // 延迟确保所有行都正确进入编辑状态
    setTimeout(async () => {
      const dataSource = rdrecords10Table.getDataSource();
      console.log('表格初始化后强制设置编辑状态');
      for (const record of dataSource) {
        // 强制进入编辑状态，确保验证回调被初始化
        await record.onEdit?.(true, false);
      }
    }, 500); // 延迟执行，确保表格完全渲染
  }

  const iqty = computed(() => {
    let sumiqty = 0;
    for (const record of rdrecords10Table.getDataSource()) {
      const {
        editValueRefs: { fqty },
      } = record;
      sumiqty += Number(fqty || 0);
    }
    return sumiqty;
  });

  function handleRdrecords10RowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRdrecords10Add() {
    if (!getFieldsValue().companyCode) {
      showMessage('请先选择公司！');
      return;
    }
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
    // rdrecords10Table.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handleRdrecords10Delete(record: Recordable) {
    rdrecords10Table.deleteTableDataRecord(record);
  }

  async function getRdrecords10List() {
    let rdrecords10ListValid = true;
    let rdrecords10List: Recordable[] = [];

    const dataSource = rdrecords10Table.getDataSource();
    console.log('验证前数据源:', dataSource);

    // 在验证前，强制确保所有行都进入编辑状态
    console.log('验证前强制初始化所有行的编辑状态');
    for (const record of dataSource) {
      await record.onEdit?.(true, false);
      console.log(`行 ${record.id} 编辑状态:`, record.editable, 'validCbs:', record.validCbs?.length);
    }

    for (const record of dataSource) {
      console.log('验证记录:', record);

      // 确保记录处于编辑状态
      if (!record.editable) {
        await record.onEdit?.(true, false);
      }

      if (!(await record.onEdit?.(false, true))) {
        console.log('记录验证失败:', record);
        rdrecords10ListValid = false;
      } else {
        console.log('记录验证成功:', record);
      }
      rdrecords10List.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rdrecords10Table.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rdrecords10List.push({
        ...record,
        status: '1',
      });
    }
    if (!rdrecords10ListValid) {
      throw { errorFields: [{ name: ['rdrecords10List'] }] };
    }
    return rdrecords10List;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rdrecord10Form(data);
    record.value = (res.rdrecord10 || {}) as Rdrecord10;
    record.value.__t = new Date().getTime();

    // 如果是新增记录，设置默认公司代码
    if (record.value.isNewRecord && userStore.getProjecte?.code) {
      record.value.companyCode = userStore.getProjecte.code;
      record.value.companyName = userStore.getProjecte.name;
      queryParams.value = {
        companyCode: record.value.companyCode,
      };
    }

    // 保存当前的公司代码值
    previousCompanyCode.value = record.value.companyCode || '';

    setFieldsValue(record.value);
    await setRdrecords10TableData(res);
    setDrawerProps({ loading: false });

    // 在表单完全加载后，再次确保所有行都处于正确的编辑状态
    setTimeout(async () => {
      const dataSource = rdrecords10Table.getDataSource();
      console.log('表单加载完成后强制设置编辑状态');
      for (const record of dataSource) {
        await record.onEdit?.(true, false);
      }
    }, 800); // 更长的延迟，确保表单完全加载
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        id: record.value.id,
      };
      data.rdrecords10List = await getRdrecords10List();
      // console.log('submit', params, data, record);
      const res = await rdrecord10Save(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }


  const totalSumRkQty = computed(() => {
    const tableData = rdrecords10Table.getDataSource();
    let sum = tableData.reduce((total, item) => total + (item.sumRkQty || 0), 0);
    // sum = sum.toFixed(2)
    return sum;
  });

  const totalFqty = computed(() => {
    // 计算总报工数
    const tableData = rdrecords10Table.getDataSource();
    let sum = tableData.reduce((total, item) => total + (item.editValueRefs.fqty || 0), 0);
    return sum;
  });
  function handleSelect(selectData) {
    selectData.forEach((item, index) => {
      rdrecords10Table.insertTableDataRecord({
        id: new Date().getTime() + index,
        isNewRecord: true,
        editable: true,
        invCode: item.invCode,
        fitemname: item.invName,
        fitemno: item.invCode,
        companyCode: item.companyCode,
        basInv: {
          viewCode: item.viewCode,
          invName: item.invName,
          funitname: item.funitname,
          // weight: item.weight,
        },
        // cfree2: item.weight,
        parent: {
          company: {
            companyName: item.company.companyName,
          },
        },
      });
    });
  }

  // handleBatchSetDcstockname 批量设置调入仓库
  async function handleBatchSetDcstockname() {
    const selectedRows = rdrecords10Table.getSelectRows();
    if (selectedRows.length === 0) {
      showMessage('请选择要设置的行！');
      return;
    }

    // 打开批量设置弹窗
    openBatchSetModal(true, {
      selectedRows: selectedRows,
    });
  }

  // 批量设置成功回调
  function handleBatchSetSuccess(updateData: any) {
    try {
      const { fdcstockno, fdcstockname, selectedRows } = updateData;

      // 批量更新选中行的调入仓库信息
      selectedRows.forEach((selectedRow: any) => {
        rdrecords10Table.updateTableDataRecord(selectedRow.id, {
          // fdcstockno: fdcstockno,
          // fdcstockname: fdcstockname,
          fstockno: fdcstockno,
          fstockname: fdcstockname,
          fstockid: fdcstockno,
        });
      });

      showMessage(`成功设置 ${selectedRows.length} 行的调入仓库信息！`);
    } catch (error) {
      console.error('批量设置失败:', error);
      showMessage('批量设置失败！');
    }
  }
</script>
<style scoped>
  .required-asterisk {
    color: red;
  }
</style>
